myApp.filter('zoneFilter', [function () {
    //根据申请描述过滤区域
    return function (zones, desc) {
        // var list = [];
        // if (desc == null || desc == '') {
        //     return zones;
        // }
        // angular.forEach(zones, function (zone) {
        //     if(arrayContains(uCloud_default_zones,zone.zone_title)){
        //         list.push(zone);
        //     }else if (desc.indexOf('"' + zone.zone_title + '"') != -1) {
        //         list.push(zone);
        //     }
        // });
        // return list;
        return zones;
    };
}]);
myApp.filter('planProFilter', [function () {
    //将项目内工程排列在最前
    return function (apps, ip, isOnlyShowPlanPro) {
        var list = [];
        angular.forEach(apps, function (app) {
            if (typeof app.plan_StateShow != 'undefined' && app.plan_StateShow != null && app.plan_StateShow) {
                list.unshift(app);
            }
            if (!isOnlyShowPlanPro && !app.plan_StateShow) {
                list.push(app);
            }
        });
        return list;
    };
}]);
myApp.controller('newucReleaseController', function ($scope, $uibModal, $stateParams, ngDialog, $http, $filter, $interval, $timeout, $rootScope) {
    $scope.ip = $stateParams.ip;
    $scope.info = {};
    $scope.info.isOnlyShowPlanPro = false;
    $scope.info.vmInfo = {};
    $scope.info.vmInfo.type = "";
    $scope.info.vmInfo.ip = "";
    $scope.info.vmStatus = "";
    $scope.info.selectVm = $stateParams.id;
    $scope.info.plan_id = $stateParams.plan_id;
    $scope.info.plan_name = $stateParams.plan_name;
    $scope.info.title = [];
    $scope.info.apps = [];

    //ucloud类型 1 未分配 2 已绑定项目 3 未绑定项目,有申请 4 集成环境未绑定计划 5 集成环境已绑定计划 6 c环境
    $scope.info.isAgent_Type = '';

    $scope.info.apps.projectInfo = [];
    $scope.info.checkAll = false;
    $scope.info.getProjectList = [];
    //执行构建的工程列表
    $scope.info.buildList = [];
    $scope.total = $scope.info.apps.length;
    $scope.page = {size: 150, index: 1};
    $scope.info.doRunList = [];
    $scope.info.msg = [];
    $scope.socket = null;
    $scope.plan_Socket = null;
    $scope.info.userRole = getUserRole();
    $scope.info.isIntegrateIp = ucIsIntegration($scope.ip);

    $scope.info.isReleaseZones = false;
    $scope.info.selectZone = {};

    $scope.info.isCEnv = arrayContains(c_ucloud_list, $stateParams.ip);

    //ucloud的内存、cpu使用情况
    $scope.info.cloudStatus = {};
    $scope.timer = null;
    $scope.getCloudStatus = function () {
        var ip = $scope.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            return;
        }
        ;
        $http.get(getUCloudAddress(ip) + "/vcloud/stat", {
            headers: {'Accept': 'application/json'}
        }).success(function (data) {
            $scope.info.cloudStatus = data;
            $scope.info.cloudStatus.memory = bytesToSize($scope.info.cloudStatus.memory);
            $scope.info.cloudStatus.memory_free = bytesToSize($scope.info.cloudStatus.memory_free);
            $scope.info.cloudStatus.disk = bytesToSize($scope.info.cloudStatus.disk);
            $scope.info.cloudStatus.disk_free = bytesToSize($scope.info.cloudStatus.disk_free);
        });
    };
    $scope.getCloudStatus();
    $scope.timer = $interval(function () {
        $scope.getCloudStatus();
    }, 120000);


    var wsObj = wsObjs[0];

    $scope.arrayContains = function (array, obj) {
        return arrayContains(array, obj);
    };

    $scope.toPlan = function (id) {
        if ($scope.info.isIntegrateIp) {
            window.location.href = "#/menu/integrationSet/" + id;
        } else {
            //根据plan id 获取plan信息 判断是否为紧急
            doBeetleGet($http, $uibModal, beetle_plan_url + '/project_plan/getPlanList?token_id=' + getTokenId() + '&plan_id=' + id + '&isShowOnline=true', function (data) {
                var plan = data.data[0];
                if (plan.isEmergency == '0') {
                    window.location.href = "#/menu/emergencyInfo/" + id;
                } else {
                    window.location.href = "#/menu/plan_ProjectList/" + id;
                }
            });
        }
    };

    $scope.$on("$destroy", function () {
        if ($scope.socket != null) {
            $scope.socket.close();
        }
        if ($scope.plan_Socket != null) {
            $scope.plan_Socket.close();
        }
        if ($scope.timer != null) {
            $interval.cancel($scope.timer);
        }
    });

    if ($scope.info.selectVm != '') {
        $http.get(ucloud_master_url + '/api/v1/agent/?token_id=' + getTokenId() + '&agent_id=' + $scope.info.selectVm).success(function (data) {
            if (data.success) {
                $scope.info.vmInfo = data.data[0];
                if ($scope.info.isIntegrateIp) {
                    $scope.info.vmInfo.type = 'QA';
                } else if ($scope.info.isCEnv) {
                    $scope.info.vmInfo.type = 'C';
                }

                $scope.getZones();
                uCloudSocket();
                planSocket();
            } else {
                alert("获取虚拟机信息为空!");
            }
            ;
        });
    } else {
        $scope.info.vmInfo = {};
    }
    ;
    $scope.getZones = function () {
        $http.get(getUCloudAddress($scope.ip) + '/zones').success(function (data) {
            $scope.info.title = data;
            $scope.info.vmStatus = "running";
            if ($scope.info.isCEnv) {
                $scope.info.isAgent_Type = '6';
            } else if ($scope.info.isIntegrateIp) {
                if ($scope.info.plan_name != "null") {
                    $scope.info.isAgent_Type = '5';
                    $http.get(beetle_plan_url + '/integration/getIntegrationProjectInfoList?isHideMergePro=true&withEmergency=true&integration_name=' + $scope.info.plan_name + '&token_id=' + getTokenId()).success(function (data) {
                        if (data.success) {
                            $scope.info.getProjectList = data.data;
                        }
                    })
                } else {
                    $scope.info.isAgent_Type = '4';
                }
            } else {
                if ($scope.info.vmInfo.plan_id != null) {
                    $scope.info.isAgent_Type = '2';
                    $http.get(beetle_plan_url + '/project_plan/getPlanProjectList?is_uc_release=true&token_id=' + getTokenId() + '&plan_id=' + $scope.info.plan_id).success(function (data) {
                        if (data.success) {
                            $scope.info.getProjectList = data.data;
                        }
                    })
                } else {
                    if ($scope.info.vmInfo.record_id != null) {
                        $scope.info.isAgent_Type = '3';
                    } else {
                        $scope.info.isAgent_Type = '1';
                    }
                }
            }
            $scope.pagelist($scope.info.title[0]);
        }).error(function () {
            $scope.info.vmStatus = "error";
        });
    };

    $scope.pagelist = function (zone) {
        $scope.info.isReleaseZones = false;
        $scope.info.selectZone = zone;
        var zone_code = zone.zone_code;
        $scope.info.apps = [];
        $http.get(getUCloudAddress($scope.ip) + '/apps?zone_code=' + zone_code).success(function (data) {
            $scope.info.vmStatus = "running";
            angular.forEach(data, function (app) {
                console.log(JSON.stringify(app));
                if (app.version != null && app.version != undefined) {
                    app.version = app.version.replace(".version", "");
                }
                app.onlineVersion = '';
                if (app.status == 'running' || app.status == 'RUNNING') {
                    app.isRunning = true;
                    $scope.doRun(app);
                } else {
                    app.isRunning = false;
                }
                ;
                if (arrayContains($scope.info.doRunList, app.app_id)) {
                    app.doRun = true;
                }
            });
            getAppInfo(data);
        }).error(function () {
            $scope.info.vmStatus = "error";
        });
    };


    $scope.wsWithReConnect = function () {
        wsWithReConnect(wsObj, function () {
            angular.forEach($scope.info.buildList, function (name) {
                wsObj.obj.send("project-" + name + "-build");
            });
        }, function (event) {
            var data = JSON.parse(event.data);
            if (data.head.type == 'project_build_status') {
                var projectName = data.body.projectName;
                var status = data.body.status;
                $scope.$apply(function () {
                    angular.forEach($scope.info.apps, function (app) {
                        if (typeof app.projectInfo != 'undefined'
                            && app.projectInfo.projectName == projectName) {
                            app.pipeline_status = status;
                            $scope.doRun(app);
                            if ("build_failed" == status) {
                                app.last_msg = '[ERROR]' + data.body.desc;
                            } else {
                                app.last_msg = data.body.desc;
                            }
                            app.projectInfo.buildStatus = status;
                            if (("build_failed" == status || "build_success" == status)) {
                                app.isRunning = false;
                                for (var i = 0; i < $scope.info.buildList.length; i++) {
                                    if (projectName == $scope.info.buildList[i]) {
                                        $scope.info.buildList.splice(i, 1);
                                        getProjectInfo(app);
                                        break;
                                    }
                                }
                            }
                        }
                    });
                });
            } else if (data.head.type == 'project_push_status') {//工程跳板机推送状态
                var projectName = data.body.projectName;
                var status = data.body.status;
                $scope.$apply(function () {
                    angular.forEach($scope.info.apps, function (app) {
                        if (typeof app.projectInfo != 'undefined'
                            && app.projectInfo.projectName == projectName) {
                            app.pipeline_status = status;
                            $scope.doRun(app);
                            if ("push_error" == status || "push_exception" == status) {
                                app.last_msg = '[ERROR]' + data.body.desc;
                            } else {
                                app.last_msg = data.body.desc;
                            }
                            app.projectInfo.pushStatus = status;
                            if ("push_success" == status || "push_error" == status || "push_exception" == status) {
                                app.isRunning = false;
                                for (var i = 0; i < $scope.info.buildList.length; i++) {
                                    if (projectName == $scope.info.buildList[i]) {
                                        $scope.info.buildList.splice(i, 1);
                                        getProjectInfo(app);
                                        break;
                                    }
                                }
                            }
                        }
                    });
                });
            }
            ;
        });
    };

    $scope.wsWithReConnect();


    function uCloudSocket() {
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            return;
        }
        ;
        $scope.socket = io.connect('http://' + ip + ':5000/notify', {'forceNew': true});
        $scope.socket.on("stat", function (msg) {
            var data = msg.data.replace(new RegExp(/(None)/g), "''");
            console.log(data);
            if (data == 'Connected' || data.indexOf('autoTest') != -1) {
                return;
            }
            data = eval("(" + data + ")");
            if (typeof data.name == 'undefined' || data.name == '') {
                return;
            }
            if (typeof data.app == 'undefined' || data.app == '') {
                return;
            }
            if (typeof data.pipeline == 'undefined' || data.pipeline == '') {
                return;
            }

            $scope.$apply(function () {
                angular.forEach($scope.info.apps, function (app) {
                    if (data.name == 'container_app_event') {
                        container_app_event(app, data);
                    }
                });
            });
        });
    };

    function planSocket() {
        $scope.plan_Socket = io.connect('http://' + beetle_plan_ip + '/notify', {'forceNew': true});
        $scope.plan_Socket.on("stat", function (msg) {
            var data = msg.data.replace(new RegExp(/(None)/g), "''");
            console.log(data)
            if (data == 'Connected') {
                return;
            }
            data = eval("(" + data + ")");
            if (data.NotifyEvent == 'plan_' + $scope.info.plan_id + '_project') {
                // console.log(data);
                $scope.$apply(function () {
                    angular.forEach($scope.info.apps, function (app) {
                        if (app.app_name == data.trunk_name) {
                            var isLock = false;
                            var editionNum = '';
                            var msg = '';
                            var type = '';
                            app.to_testCan_publish = false;
                            app.integrationCan_publish = false;
                            if (app.plan_project.to_test_edition != data.to_test_edition) {
                                isLock = true;
                                if (data.to_test_edition == null) {
                                    editionNum = app.plan_project.to_test_edition
                                    msg = '取消提测';
                                } else if (app.plan_project.to_test_edition == null || app.plan_project.to_test_edition != data.to_test_edition) {
                                    app.to_testCan_publish = true;
                                    editionNum = data.to_test_edition;
                                    msg = '进行提测';
                                    type = '有待发布状态，请查看';
                                }

                            } else if (app.plan_project.testing_edition != data.testing_edition) {
                                isLock = true;
                                if (data.testing_edition == null) {
                                    editionNum = app.plan_project.testing_edition;
                                    msg = '取消测试'

                                } else if (app.plan_project.testing_edition == null || app.plan_project.testing_edition != data.testing_edition) {
                                    editionNum = data.testing_edition;
                                    msg = '测试 并发布版本'
                                }
                            } else if (app.plan_project.to_integration_edition != data.to_integration_edition) {
                                isLock = true;
                                if (data.to_integration_edition == null) {
                                    editionNum = app.plan_project.to_integration_edition;
                                    msg = '取消转测'
                                } else if (app.plan_project.to_integration_edition == null || app.plan_project.to_integration_edition != data.to_integration_edition) {
                                    editionNum = data.to_integration_edition;
                                    msg = '进行转测'
                                }
                            } else if (app.plan_project.integration_edition != data.integration_edition) {
                                isLock = true;
                                if (data.integration_edition == null) {
                                    editionNum = app.plan_project.integration_edition;
                                    msg = '不可集成'
                                } else if (app.plan_project.integration_edition == null || app.plan_project.integration_edition != data.integration_edition) {
                                    editionNum = data.integration_edition;
                                    app.integrationCan_publish = true;
                                    type = '有待发布状态，请查看';
                                    msg = '可集成'

                                }

                            } else if (app.plan_project.integrationing_edition != data.integrationing_edition) {
                                isLock = true;
                                if (data.integrationing_edition == null) {

                                    editionNum = app.plan_project.integrationing_edition;
                                    msg = '取消集成测试'
                                } else if (app.plan_project.integrationing_edition == null || app.plan_project.integrationing_edition != data.integrationing_edition) {
                                    editionNum = data.integrationing_edition;
                                    msg = '进行集成测试'
                                }

                            } else if (app.plan_project.hand_over_edition != data.hand_over_edition) {
                                isLock = true;
                                if (data.hand_over_edition == null) {
                                    editionNum = app.plan_project.hand_over_edition;
                                    msg = '取消交付';
                                } else if (app.plan_project.hand_over_edition == null || app.plan_project.hand_over_edition != data.hand_over_edition) {
                                    editionNum = data.hand_over_edition;
                                    msg = '进行交付';

                                }
                            }
                            if (isLock) {
                                app.plan_project = data;
                                getProjectInfo(app);
                                app.plan_show_msg = app.projectInfo.projectName + '版本更新:' + msg + '.版本号:' + editionNum + ':' + type
                            }
                        }
                    });
                });
            }
        });
    };

    function container_app_event(app, data) {
        if (app.app_id == data.app.app_id) {
            $scope.doRun(app);
            app.pipeline_status = data.pipeline.status;
            app.status = data.app.status;
            app.is_running = data.app.is_running;
            app.last_msg = data.app.last_msg;
            app.running_pipeline = data.app.running_pipeline;
            app.db_dump_create_date = data.app.db_dump_create_date;
            app.app_package_create_date = data.app.app_package_create_date;
            if (data.app.running_pipeline != null) {
                app.isRunning = true;
                return;
            }
            app.isRunning = false;

            if (app.pipeline_status == 'DONE') {
                app.version = data.app.version.replace('.version', '');
            }
        }
    }


    //应用状态中文显示
    function getAppStatusZN(app) {
        if (typeof app.status == 'undefined' || app.status == 'undefined'
            || app.status == null || app.status == 'null') {
            return "";
        }
        if (app.status == "unavailable") {
            return "未部署";
        } else if (app.status == "ready") {
            return "已部署";
        } else if (app.running_pipeline != null) {
            return "执行操作";
        }
    };
    //展示应用状态图标
    $scope.showStatusIcon = function (app) {
        app.statusTip = '<table class="table table-bordered">';
        if (typeof app.status == 'undefined' || app.status == 'undefined'
            || app.status == null || app.status == 'null') {
            app.statusTip += '<tr><td>应用状态:</td><td></td></tr>';
        } else {
            app.statusTip += '<tr><td>应用状态:</td><td>' + getAppStatusZN(app);
            +'</td></tr>';
        }
        if (app.running_pipeline != null) {
            var pipName = app.running_pipeline.replace("_install", "安装").replace("_stop", "停应用").replace("_restart", "重启应用");
            app.statusTip += '<tr><td>任务状态:</td><td>' + pipName + '</td></tr>';
        } else {
            app.statusTip += '<tr><td>任务状态:</td><td></td></tr>';
        }
        app.statusTip += '</table>';

        if (app.isRunning) {
            // if(app.running_pipeline != null || app.isRunning){
            return "";
        } else if (app.is_running) {
            return "running";
        } else if (!app.is_running) {
            return "stop";
        }

        return '';
    };


    //根据app列表查询beetle版本信息
    function getAppInfo(apps) {
        if (apps.length == 0) {
            return;
        }

        var param = [];
        angular.forEach(apps, function (app) {
            if (app.on_beetle == 'true') {
                var obj = new Object();
                obj.name = app.app_name;
                obj.version = app.version;
                obj.type = app.app_type;
                param.push(obj);
            }
        });

        $http.post(java_url + '/beetle/uCloud/getUCloudProjectInfo', {
            tokenId: getTokenId(),
            param: JSON.stringify(param)
        }).success(function (data) {
            angular.forEach(apps, function (app) {
                app.plan_StateShow = false;
                app.msg = "";
                for (var i in ucloud_project_url) {
                    var url = ucloud_project_url[i];
                    if (url.name == app.app_name) {
                        app.ucUrl = url.url;
                        if (url.https) {
                            app.ucHttps = url.https;
                        } else {
                            app.ucHttps = false;
                        }
                        if (url.https_type) {
                            app.https_type = url.https_type;
                        } else {
                            app.https_type = 'nginx';
                        }
                        if (url.port) {
                            app.ucPort = url.port;
                        }
                        if (url.https_zones) {
                            app.https_zones = url.https_zones;
                        } else {
                            app.https_zones = '';
                        }
                        break;
                    }
                }
                for (var i in data.data.list) {
                    var data_app = data.data.list[i];
                    if (app.app_name == data_app.trunkName) {
                        app.projectList = data_app.projectList;
                        app.projectInfo = data_app.projectInfo;
                        app.editionList = data_app.editionList;
                        app.editionInfo = data_app.editionInfo;
                        app.onlineVersion = data_app.onlineVersion;
                        app.qaTestVersion = data_app.qaTestVersion;
                        break;
                    }
                }
                for (var i in $scope.info.getProjectList) {
                    var project = $scope.info.getProjectList[i];
                    if (app.app_name == project.trunk_name) {
                        app.plan_project = project;
                        app.plan_StateShow = true;
                        break;
                    }
                }
            });
            $scope.info.apps = apps;
        });
    };

    //全选事件
    $scope.checkAll = function () {

        angular.forEach($scope.info.apps, function (app) {
            app.check = $scope.info.checkAll;
        });
    };

    //切换线上版本
    $scope.goOnlineVersion = function () {
        openDialog(ngDialog, $scope, "将选中的项目切换线上版本,确认吗?", true, function (val) {
            if (!val) {
                return;
            }

            angular.forEach($scope.info.apps, function (app) {
                if (app.check && app.on_beetle == 'true' && app.app_type != 'adempiere') {
                    if (typeof app.onlineVersion != 'undefined' && app.onlineVersion != null
                        && app.onlineVersion != '') {
                        var project = app.onlineVersion.split("#")[0];
                        var edition = app.onlineVersion.split("#")[1];
                        for (var i in app.projectList) {
                            var pro = app.projectList[i];
                            if (pro.projectName == project) {
                                app.editionNum = edition;
                                app.projectInfo = pro;
                                $scope.projectChange(app);
                                break;
                            }
                        }
                    } else {
                        if ($scope.info.isCEnv) {
                            app.check = false;
                        }
                    }
                } else {
                    if ($scope.info.isCEnv) {
                        app.check = false;
                    }
                }
            });
        });
    };

    //切换项目版
    $scope.goPlanVersion = function () {
        openDialog(ngDialog, $scope, "将选中的项目切换项目版本,确认吗?", true, function (val) {
            if (!val) {
                return;
            }

            //1.集成环境调用查询集成计划内的工程
            if ($scope.info.isIntegrateIp) {
                $http.get(beetle_plan_url + '/integration/getIntegrationProjectEditionList?token_id=' + getTokenId() + '&integration_id=' + $scope.info.plan_id).success(function (data) {
                    if (data.success == true) {
                        angular.forEach($scope.info.apps, function (app) {
                            if (app.check && app.plan_StateShow && app.on_beetle == 'true' && app.app_type != 'adempiere') {
                                $scope.changePlanPro(app, data);
                            }
                        });
                    } else {
                        alert(data.msg);
                        return false;
                    }
                })
            } else {
                $http.get(beetle_plan_url + '/project_plan/getPlanProjectEditionList?is_uc_release=true&token_id=' + getTokenId() + '&plan_id=' + $scope.info.plan_id).success(function (data) {
                    if (data.success == true) {
                        angular.forEach($scope.info.apps, function (app) {
                            if (app.check && app.plan_StateShow && app.on_beetle == 'true' && app.app_type != 'adempiere') {
                                $scope.changePlanPro(app, data);
                            }
                        });
                    } else {
                        alert(data.msg);
                        return false;
                    }
                })
            }
        })
    };

    $scope.isSwitchShow = function (app) {
        if (app.plan_project == undefined
            || app.plan_project == null
            || typeof app.version == 'undefined'
            || app.version == undefined
            || app.to_testCan_publish
            || app.integrationCan_publish) {
            return false;
        }
        if (app.plan_project.isOnBeetle == '0' && app.plan_project.package_type == 'maven_jar') {
            return false;
        }
        if (app.plan_project.isOnBeetle == '1' && app.plan_project.package_type != 'ad') {
            return false;
        }
        //java工程
        if (app.version.split('@').length == 2) {
            if ($scope.info.isIntegrateIp) {
                if (app.plan_project.integration_edition != null && app.version.split('@')[1] != app.plan_project.integration_edition) {
                    return true;
                }
            } else {
                if (app.plan_project.to_test_edition != null && app.version.split('@')[1] != app.plan_project.to_test_edition) {
                    return true;
                }
            }
        } else {//ad /-1
            if ($scope.info.isIntegrateIp) {
                if (app.plan_project.integration_edition != null && app.version != app.plan_project.integration_edition) {
                    return true;
                }
            } else {
                if (app.plan_project.to_test_edition != null && app.version != app.plan_project.to_test_edition) {
                    return true;
                }
            }
        }
        return false;
    };

    //当socket有新版本通知或者进入页面发现当前部署版本不是项目版本时，点击按钮发布项目版本
    $scope.changePlanBranch = function (app, isRelease) {
        if (app.plan_project == undefined || app.plan_project == null) {
            openDialogAlert(ngDialog, $scope, "工程" + app.app_name + "不在项目内,不能切换!");
            return;
        }

        var saveFun = function (data) {
            app.plan_project = data[0];

            $scope.notReleaseNewEdition(app);
            app.isChanging = true;

            if ($scope.info.isIntegrateIp) {
                app.editionNum = app.plan_project.integration_edition;
            } else {
                app.editionNum = app.plan_project.to_test_edition;
            }

            if (app.plan_project.package_type == 'maven_war' || app.plan_project.package_type == 'php' || app.plan_project.package_type == 'spring_boot_jar') {
                angular.forEach(app.projectList, function (pro) {
                    if (pro.projectName == app.plan_project.project_name) {
                        app.projectInfo = pro;
                        $scope.projectChange(app, isRelease);
                    }
                });
            } else if (app.plan_project.package_type == 'ad') {
                angular.forEach(app.projectList, function (pro) {
                    if (pro.projectName.indexOf('build') != -1) {
                        app.projectInfo = pro;
                        $scope.projectChange(app, isRelease);
                    }
                });
            }
        };

        //1.集成环境 要切换的版本为可以集成版本
        if ($scope.info.isIntegrateIp) {
            $rootScope.editionIntegrationTemplate(app.plan_project.project_name, 'INTEGRATION', saveFun);
        }
        //2.普通环境  要切换的版本为提测版本
        else {
            $rootScope.editionIntegrationTemplate(app.plan_project.project_name, 'TEST', saveFun);
        }
    };

    $scope.changePlanPro = function (app, data, isRelease) {
        angular.forEach(data.data, function (p_data) {
            if (p_data.app == app.app_name) {
                angular.forEach(app.projectList, function (pro) {
                    if (pro.projectName == p_data.projectName) {
                        app.projectInfo = pro;
                        if ($scope.info.isIntegrateIp) {
                            if (app.plan_project.integration_edition != undefined && app.plan_project.integration_edition != null) {
                                app.editionNum = app.plan_project.integration_edition;
                            } else {
                                app.editionNum = p_data.editionNum;
                            }
                        } else {
                            if (app.plan_project.to_test_edition != undefined && app.plan_project.to_test_edition != null) {
                                app.editionNum = app.plan_project.to_test_edition;
                            } else {
                                app.editionNum = p_data.editionNum;
                            }
                        }
                        $scope.projectChange(app, isRelease);
                    }
                });
            }
        })
    };

    //重启agent
    $scope.restartAgent = function () {
        openDialog(ngDialog, $scope, "将重启agent,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/st?token_id=' + getTokenId() + '&agent_id=' + $scope.info.selectVm).success(function (data) {
                if (data.success == true) {
                    openDialogAlert(ngDialog, $scope, "重启中,稍后请刷新页面...");
                } else {
                    openDialogAlert(ngDialog, $scope, data.msg);
                }
            })
        })
    };

    //升级agent
    $scope.initAgent = function () {
        openDialog(ngDialog, $scope, "将升级agent,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/agent/init?token_id=' + getTokenId() + '&agent_id=' + $scope.info.selectVm).success(function (data) {
                if (data.success == true) {
                    openDialogAlert(ngDialog, $scope, "升级中,稍后请刷新页面...");
                } else {
                    openDialogAlert(ngDialog, $scope, data.msg);
                    return false;
                }
            })
        })

    };

    //查看API
    $scope.goAPI = function () {
        window.open("http://" + $scope.ip + ":5000/api/v1");
    };

    $scope.openApp = function (app) {
        var url = "";
        var port = app.port;
        if (!app.ucHttps) {
            url = "http://";
        } else {
            if (app.https_type == 'nginx' && app.ucPort && app.zone_code == 'uc.gzidc.area') {
                url = "https://";
                port = app.ucPort;
            } else if (app.https_type == 'apache' && app.https_zones.indexOf(',' + app.zone_code + ',') != -1) {
                url = "https://";
            } else {
                url = "http://";
            }
        }
        window.open(url + $scope.info.vmInfo.ip + ":" + port + app.ucUrl);
    };
    // 构建
    $scope.doBuild = function (app) {
        openDialog(ngDialog, $scope, "确定要进行构建吗?", true, function (flag) {
            if (!flag) {
                return;
            }


            if (app.isRunning) {
                return;
            }
            $scope.doRun(app);
            app.isRunning = true;
            // app.runTip = "工程构建中";
            app.pipeline_status = '';
            app.last_msg = '';
            $http.post(java_url + '/beetle/project/doBuild', {
                projectName: app.projectInfo.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert(data.desc);
                    return;
                }
                ;
                getProjectInfo(app);
                $scope.info.buildList.push(app.projectInfo.projectName);
                wsObj.obj.send("project-" + app.projectInfo.projectName + "-build");
            });
        });
    };
    //部署
    $scope.doRelease = function (app) {
        var saveFun = function (data) {
            $scope.info.isReleaseZones = data.check;
            release(app);
        };

        $rootScope.checkAlertTemplate("确定要发布该版本么?", "同时发布其他区域", saveFun);
    };

    function release(app) {
        var param = new Object();
        param.package_path = "";
        param.version = "";
        param.sub_path = "";
        if (app.on_beetle == "true") {
            if (typeof app.projectInfo.projectName == 'undefined'
                || typeof app.editionInfo.editionNum == 'undefined') {
                openDialog(ngDialog, $scope, "所选分支或版本不存在,请重新选择!", false, function () {
                });
                return;
            }

            if (app.editionInfo.editionNum == 'default'
                && app.projectInfo.buildStatus != 'build_success') {
                openDialog(ngDialog, $scope, "该版本尚未构建或构建失败,请构建成功后再发布!", false, function () {
                });
                return;
            }

            if (app.app_type == 'adempiere') {
                param.package_path = app.projectInfo.projectName + "/" + app.editionInfo.editionNum;
                param.version = app.editionInfo.editionNum;
            } else if (app.app_type == 'tomcat' || app.app_type == 'php' || app.app_type == 'spring-boot') {
                param.package_path = getEditionPath(app.projectInfo.projectName, app.editionInfo.editionNum);
                param.version = app.projectInfo.projectName + "@" + app.editionInfo.editionNum;
                param.sub_path = "/target";
                if (typeof app.editionInfo.nasNum != 'undefined'
                    && app.editionInfo.nasNum != 'undefined'
                    && app.editionInfo.nasNum != ''
                    && app.editionInfo.nasNum != null) {
                    param.sub_path = param.sub_path + "/" + app.editionInfo.nasNum;
                }
                ;
            }
        }
        // app.runTip = "应用发布中";
        $scope.releaseZones(app.app_id + "_install", param);
        $scope.runPipeline(app, app.app_id + "_install", param);
    };


    $scope.batchRelease = function () {
        openDialog(ngDialog, $scope, "将跳过未构建的应用,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            angular.forEach($scope.info.apps, function (app) {
                if (app.check) {
                    if (app.on_beetle == "true") {
                        if (typeof app.projectInfo != 'undefined'
                            && typeof app.editionInfo != 'undefined'
                            && typeof app.projectInfo.projectName != 'undefined'
                            && typeof app.editionInfo.editionNum != 'undefined') {
                            if (app.editionInfo.editionNum != 'default'
                                || (app.editionInfo.editionNum == 'default'
                                    && app.projectInfo.buildStatus == 'build_success')) {
                                release(app);
                            }
                        }
                    } else {
                        release(app);
                    }
                }
            });
        });
    };


    $scope.restartArea = function () {
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            alert("虚拟机ip为空!");
            return;
        }
        ;
        openDialog(ngDialog, $scope, "请确认是否启动【" + $scope.info.selectZone.zone_title + "】所有应用？", true, function (val) {
            if (!val) {
                return;
            }
            var url = 'http://' + ip + ':5000/api/v1/apps/startApps?zone_code=' + $scope.info.selectZone.zone_code;
            doBeetleGet($http, $uibModal, url, function (data) {
                openDialogAlert(ngDialog, $scope, "调用agent成功,请稍后查看应用启动状态!");
            })
        });
    };


    // 停止
    $scope.doStop = function (app) {
        //php应用不需要停止
        if (app.app_type == 'php') {
            alert("php应用不需要进行重启！");
            return
        }

        openDialog(ngDialog, $scope, "确定要停止该应用么?", true, function (flag) {
            if (!flag) {
                return;
            }
            stop(app);
        });
    };


    //停止
    function stop(app) {
        var param = new Object();
        $scope.runPipeline(app, app.app_id + "_stop", param);
    };

    //启动
    $scope.doRestart = function (app) {
        var saveFun = function (data) {
            $scope.info.isReleaseZones = data.check;
            restart(app);
        };
        $rootScope.checkAlertTemplate("确定要重启该应用么?", "同时重启其他区域", saveFun);
    };

    function restart(app) {
        var param = new Object();
        var pipeline_name = app.app_id + "_restart";
        $scope.doRun(app);
        app.isRunning = true;
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            alert("虚拟机ip为空!");
            return;
        }
        ;
        app.pipeline_status = "running";
        app.last_msg = "";
        $http.get(getUCloudAddress(ip) + "/apps/start?params=" + JSON.stringify(param) + "&pipeline_name=" + pipeline_name, {
            headers: {'Accept': 'application/json'}
        }).success(function (data) {
            app.pipeline_status = data.status;
        }).error(function () {
            $scope.info.vmStatus = "error";
        });
        $scope.releaseZones(app.app_id + "_restart", param);
    };


    //批量重启应用
    $scope.batchRestart = function () {
        openDialog(ngDialog, $scope, "将跳过php应用和执行中的应用,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            angular.forEach($scope.info.apps, function (app) {
                if (app.check && app.app_type != 'php' && !app.isRunning) {
                    // $scope.doRestart(app);
                    restart(app);
                }
            });
        });
    };

    //修复dep
    $scope.fixApp = function (app) {
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            alert("虚拟机ip为空!");
            return;
        }
        ;
        alert("adfas");
        // $http.get(getUCloudAddress(ip)+"/apps/?zone_code="+zone.zone_code,{
        //     headers : {'Accept':'application/json'},
        // }).success(function (data) {
        // }).error(function () {
        //     $scope.info.vmStatus="error";
        // });
    };

    //重新导入应用数据库数据
    $scope.reImportData = function (app) {
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            alert("虚拟机ip为空!");
            return;
        }
        ;
        var db_name = 'pip-db:' + app.db_type + ':' + app.db_name + ':demo';

        openDialog(ngDialog, $scope, "确定要重新导入" + app.app_name + "的数据库么?", true, function (val) {
            if (!val) {
                return;
            }
            openDialog(ngDialog, $scope, "重新导入后,之前的数据将删除,是否确认导入？", true, function (val) {
                if (!val) {
                    return;
                }
                $.ajax({
                    type: "put",
                    url: getUCloudAddress(ip) + '/database/import?db_name=' + db_name,
                    dataType: "JSON",
                    contentType: "application/json",
                    async: false,
                    success: function () {
                        openDialog(ngDialog, $scope, "重新导入成功，请在日志查看导入结果!", false, function (val) {
                        });
                    }
                });
            });
        });
    };

    //批量停止
    $scope.batchStop = function () {
        openDialog(ngDialog, $scope, "将跳过php应用和执行中的应用,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            angular.forEach($scope.info.apps, function (app) {
                if (app.check && app.app_type != 'php' && !app.isRunning) {
                    // $scope.doRestart(app);
                    stop(app);
                }
            });
        });
    };


    $scope.runPipeline = function (app, pipeline_name, param) {
        if (app.isRunning) {
            return;
        }
        $scope.doRun(app);
        app.isRunning = true;
        var ip = $scope.info.vmInfo.ip;
        if (typeof ip == 'undefined'
            || ip == 'undefined'
            || ip == '') {
            alert("虚拟机ip为空!");
            return;
        }
        ;
        app.pipeline_status = "running";
        app.last_msg = "";
        $http.get(getUCloudAddress(ip) + "/apps/start?params=" + JSON.stringify(param) + "&pipeline_name=" + pipeline_name, {
            headers: {'Accept': 'application/json'}
        }).success(function (data) {
            app.pipeline_status = data.status;
        }).error(function () {
            $scope.info.vmStatus = "error";
        });
    };

    $scope.releaseZones = function (pipeline_name, param) {
        if (!$scope.info.isReleaseZones) {
            return;
        }
        angular.forEach($scope.info.title, function (zone) {
            if (zone.zone_code == "uc.gzidc.area") {
                return;
            }
            if (zone.zone_code == $scope.info.selectZone.zone_code) {
                return;
            }
            if (zone.zone_title.substring(zone.zone_title.length - 1, zone.zone_title.length) != $scope.info.selectZone.zone_title.substring($scope.info.selectZone.zone_title.length - 1, $scope.info.selectZone.zone_title.length)) {
                return;
            }
            var pipeline = pipeline_name.replace($scope.info.selectZone.zone_alias, zone.zone_alias);
            console.log(pipeline);
            $http.get(getUCloudAddress($scope.info.vmInfo.ip) + "/apps/start?params=" + JSON.stringify(param) + "&pipeline_name=" + pipeline, {
                headers: {'Accept': 'application/json'}
            }).success(function (data) {
                console.log("pipeline=" + pipeline + ",param=" + JSON.stringify(param) + ",data=" + JSON.stringify(data));
            }).error(function () {
            });
        });
        $scope.info.isReleaseZones = false;
    };

    $scope.doRun = function (app) {
        app.doRun = true;
        if (!arrayContains($scope.info.doRunList, app.app_id)) {
            $scope.info.doRunList.push(app.app_id);
        }
    };

//刷新选中工程的信息
    function getProjectInfo(app, isRelease) {
        if (typeof app.projectInfo == 'undefined'
            || app.editionInfo == 'undefined') {
            return;
        }
        $http.post(java_url + '/beetle/project/projectListByTrunk', {
            tokenId: getTokenId(),
            trunkName: app.app_name
        }).success(function (data) {
            if (data.code == '0') {
                app.projectList = data.data.list;
                angular.forEach(app.projectList, function (pro) {
                    if (pro.projectName == app.projectInfo.projectName) {
                        app.projectInfo = pro;
                        // app.editionNum = app.editionInfo.editionNum;
                        $scope.projectChange(app, isRelease);
                    }
                });
            }
        });

    };

    //project变动
    $scope.projectChange = function (app, isRelease) {
        if (app.app_type == 'adempiere') {
            $http.post(java_url + '/beetle/uCloud/adEditionList', {
                projectName: app.projectInfo.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                app.isChanging = false;
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                }
                ;
                app.editionList = data.data.list;
                if (app.editionNum == '') {
                    app.editionInfo = data.data.list[0];
                    app.editionNum = app.editionInfo.editionNum;
                } else {
                    var count = 0;
                    angular.forEach(data.data.list, function (edi) {
                        if (edi.editionNum == app.editionNum) {
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if (count == 0) {
                        app.editionInfo = data.data.list[0];
                    }
                }
                ;
                if (isRelease) {
                    release(app);
                }
            });
        } else {
            $http.post(java_url + '/beetle/project/editionInfoList', {
                projectName: app.projectInfo.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                app.isChanging = false;
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                }
                ;
                app.editionList = data.data.list;
                if (app.editionNum == '') {
                    if (data.data.list.length > 1) {
                        app.editionInfo = data.data.list[1];
                    } else {
                        app.editionInfo = data.data.list[0];
                    }
                    app.editionNum = app.editionInfo.editionNum;
                } else {
                    var count = 0;
                    angular.forEach(data.data.list, function (edi) {
                        if (edi.editionNum == app.editionNum) {
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if (count == 0) {
                        if (data.data.list.length > 1) {
                            app.editionInfo = data.data.list[1];
                        } else {
                            app.editionInfo = data.data.list[0];
                        }
                    }
                }
                ;
                if (isRelease) {
                    if (app.editionInfo.editionNum == 'default'
                        && app.projectInfo.buildStatus != 'build_success') {
                        openDialog(ngDialog, $scope, "该版本尚未构建或构建失败,请构建成功后再发布!", false, function () {
                        });
                        return;
                    } else {
                        release(app);
                    }
                }
            });
        }
    };


    // 提测
    $scope.goLift_test = function (app) {
        if (app.plan_project.project_name == app.projectInfo.projectName) {
            var saveFun = function (data) {
                app.plan_project = data[0];
                app.editionNum = app.plan_project.to_test_edition;
                getProjectInfo(app)
            };

            $rootScope.editionToTestTemplate(app.plan_project.project_name, 'TEST', saveFun);
        }
    };
    // 取消提测
    $scope.goCancel_Lift_test = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目取消提测,确认吗?", true, function (val) {
            if (!val) {
                return;
            }

            if (app.plan_project.project_name == app.projectInfo.projectName) {
                $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=cancel_to_test&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                    if (data.success == true) {
                        app.plan_project = data.data[0];
                        getProjectInfo(app)
                    } else {
                        angular.forEach($scope.info.apps, function (Infoapps) {
                            if (Infoapps.app_name == app.app_name) {
                                app.msg = data.msg;
                            }
                        });
                        return false;
                    }
                })
            }
        })
    };

    // 测试
    $scope.goTest = function (app) {
        if (app.plan_project.project_name == app.projectInfo.projectName) {
            var saveFun = function (data) {
                app.to_testCan_publish = false;
                app.plan_project = data[0];
                getProjectInfo(app, true);
                // release(app);
            };

            $rootScope.editionIntegrationTemplate(app.plan_project.project_name, 'TEST', saveFun);
        }
    };
    // 取消测试
    $scope.goCancel_Test = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目取消测试,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            if (app.plan_project.project_name == app.projectInfo.projectName) {
                $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=cancel_test&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                    if (data.success == true) {
                        app.plan_project = data.data[0];
                        getProjectInfo(app)

                    } else {
                        angular.forEach($scope.info.apps, function (Infoapps) {
                            if (Infoapps.app_name == app.app_name) {
                                app.msg = data.msg;
                            }
                        });
                        return false;
                    }
                })
            }
        })
    };
    // 转测
    $scope.goTurn_test = function (app) {
        if (app.plan_project.project_name == app.projectInfo.projectName) {
            var saveFun = function (data) {
                app.plan_project = data[0];
                getProjectInfo(app)
            };

            $rootScope.editionToTestTemplate(app.plan_project.project_name, 'INTEGRATION', saveFun);
        }
    };
    // 取消转测cancel_to_integration
    $scope.goCancel_Turn_test = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目取消转测,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            if (app.plan_project.project_name == app.projectInfo.projectName) {
                $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=cancel_to_integration&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                    if (data.success == true) {
                        app.plan_project = data.data[0];
                        getProjectInfo(app)
                    } else {
                        angular.forEach($scope.info.apps, function (Infoapps) {
                            if (Infoapps.app_name == app.app_name) {
                                app.msg = data.msg;
                            }
                        });
                        return false;
                    }
                })
            } else {

            }
        })
    };
    // 可集成can_integration
    $scope.goCan_Integration = function (app) {
        if (app.plan_project.project_name == app.projectInfo.projectName) {
            var saveFun = function (data) {
                app.plan_project = data[0];
                getProjectInfo(app)
            };

            $rootScope.editionIntegrationTemplate(app.plan_project.project_name, 'CAN_INTEGRATION', saveFun);
        }
    };
    // 不可集成can_not_integration
    $scope.goCNIntegrate = function (app) {
        $scope.goCan_Integration(app);
    };
    // 集成integration
    $scope.goIntegrate = function (app) {
        if (app.plan_project.project_name == app.projectInfo.projectName) {
            var saveFun = function (data) {
                app.integrationCan_publish = false;
                app.plan_project = data[0];
                app.editionNum = app.plan_project.integrationing_edition;
                getProjectInfo(app, true);
            };
            $rootScope.editionIntegrationTemplate(app.plan_project.project_name, 'INTEGRATION', saveFun);
        }
    };
    // 取消集成can_not_integration
    $scope.goCancel_Integrate = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目取消集成,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=cancel_integration&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                if (data.success == true) {
                    app.plan_project = data.data[0];
                    getProjectInfo(app)
                } else {
                    angular.forEach($scope.info.apps, function (Infoapps) {
                        if (Infoapps.app_name == app.app_name) {
                            app.msg = data.msg;
                        }
                    })
                    return false;
                }
            })
        })
    }
    // 交付hand_over
    $scope.goDeliver = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目进行交付,确认吗?", true, function (val) {
            if (!val) {
                return;
            }

            if (app.plan_project.package_type == 'ad' || app.plan_project.project_name == app.projectInfo.projectName) {
                $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=hand_over&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                    if (data.success == true) {
                        app.plan_project = data.data[0];
                        getProjectInfo(app)
                    } else {
                        angular.forEach($scope.info.apps, function (Infoapps) {
                            if (Infoapps.app_name == app.app_name) {
                                app.msg = data.msg;
                            }
                        });
                        return false;
                    }
                })
            } else {

            }
        })
    };
    // 取消交付cancel_hand_over
    $scope.goCancel_Deliver = function (app) {
        openDialog(ngDialog, $scope, "将选中的项目取消交付,确认吗?", true, function (val) {
            if (!val) {
                return;
            }
            if (app.plan_project.project_name == app.projectInfo.projectName) {
                $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + app.plan_project.project_name + '&type=cancel_hand_over&edition_num=' + app.editionInfo.editionNum + '&plan_id=' + app.plan_project.plan_id).success(function (data) {
                    if (data.success == true) {
                        app.plan_project = data.data[0];
                        getProjectInfo(app)
                    } else {
                        angular.forEach($scope.info.apps, function (Infoapps) {
                            if (Infoapps.app_name == app.app_name) {
                                app.msg = data.msg;
                            }
                        });
                        return false;
                    }
                })
            } else {

            }
        })
    };
    //当websocket推送新版版本，点击不发布，修改状态标签
    $scope.notReleaseNewEdition = function (app) {
        if (app.to_testCan_publish) {
            app.to_testCan_publish = false;
        }
        if (app.integrationCan_publish) {
            app.integrationCan_publish = false;
        }
    };

    //交付流程 show

    $scope.plan_StateShow = function (app) {
        var isShow = false;
        if (app.plan_StateShow == true && app.projectInfo != undefined && app.plan_project != undefined) {
            if (app.projectInfo.projectName == app.plan_project.project_name) {
                isShow = true;
            }
        }
        return isShow;
    };

// 按钮权限
    $scope.agentShowType = function (app) {
        var showList = {};
        showList.Build = false; // 构建
        showList.Release = false; // 发布
        showList.SwitchShow = false;// 切换
        //交付流程
        showList.Lift_test = false;//提测
        showList.Cancel_Lift_test = false;//取消提测
        showList.Test = false;//测试
        showList.Cancel_Test = false;//取消测试
        showList.Turn_test = false;//转测
        showList.Cancel_Turn_test = false;//取消转测
        showList.Can_Integration = false;//可集成
        showList.CNIntegrate = false;//不可集成
        showList.Integrate = false;// 集成
        showList.Cancel_Integrate = false;//取消集成
        showList.Deliver = false;//交付
        showList.Cancel_Deliver = false;//取消交付

        //发布
        if ($scope.roleShow()) {
            showList.Release = true;
            if (app.on_beetle == 'true') {
                if (app.editionInfo == undefined || (app.editionInfo.editionNum == 'default' && app.editionInfo.showNum.indexOf('构建成功') == -1)) {
                    showList.Release = false;
                }
            }
        }
        if ($scope.info.isAgent_Type == '1') {
            showList.SwitchShow = true;// 切换
        } else if ($scope.info.isAgent_Type == '2') {
            if (app.plan_StateShow && $scope.plan_StateShow(app) && $scope.roleShow() && (isUserCanOperateByRole('dev')) && app.editionInfo != undefined && app.editionInfo.editionNum == 'default') {
                showList.Build = true;
            }
            if ($scope.roleShow()) {
                if (app.plan_StateShow || app.app_type == 'adempiere' || isUserCanOperateByRole('plan_admin', 'ucloud_admin')
                    || (isUserCanOperateByRole('dev') && $scope.info.vmInfo.type.toLowerCase() == 'dev')) {
                    showList.SwitchShow = true;
                }
            }

            if (app.plan_project != undefined && app.plan_project.plan_id == $scope.info.plan_id && typeof app.editionInfo != "undefined" && app.editionInfo != null && app.editionInfo != '' && app.editionInfo != undefined && app.editionInfo.editionNum != undefined) {
                if ($scope.roleShow() && $scope.plan_StateShow(app) && ($scope.arrayContains($scope.info.userRole, 'admin') || $scope.arrayContains($scope.info.userRole, 'dev'))) {
                    showList.Lift_test = true;//提测
                    showList.Cancel_Lift_test = true;//取消提测
                }
                if ($scope.roleShow() && $scope.plan_StateShow(app) && ($scope.arrayContains($scope.info.userRole, 'admin') || $scope.arrayContains($scope.info.userRole, 'qa'))) {
                    showList.Test = true;//测试
                    showList.Cancel_Test = true;//取消测试
                    showList.Turn_test = true;//转测
                    showList.Cancel_Turn_test = true;//取消转测
                }
                if ($scope.arrayContains($scope.info.userRole, 'admin')) {
                    showList.Can_Integration = true;//可集成
                    showList.CNIntegrate = true;//不可集成
                    showList.Integrate = true;// 集成
                    showList.Cancel_Integrate = true;//取消集成
                    showList.Deliver = true;//交付
                    showList.Cancel_Deliver = true;//取消交付
                }
            }
        } else if ($scope.info.isAgent_Type == '3') {
            if ($scope.roleShow() && ($scope.arrayContains($scope.info.userRole, 'admin') || $scope.arrayContains($scope.info.userRole, 'dev')) && app.editionInfo.editionNum == 'default') {
                showList.Build = true;
            }
            showList.SwitchShow = true;// 切换
        } else if ($scope.info.isAgent_Type == '4') {
            if (isUserCanOperateByRole("plan_admin")) {
                showList.SwitchShow = true;// 切换
            }

            if (typeof app.editionInfo != "undefined" && app.editionInfo != null && app.editionInfo != '' && app.editionInfo != undefined && app.editionInfo.editionNum != undefined) {
                if (isUserCanOperateByRole("plan_admin", "pm", "qa")) {
                    showList.Integrate = true;// 集成
                    showList.Cancel_Integrate = true;//取消集成
                    showList.Deliver = true;//交付
                    showList.Cancel_Deliver = true;//取消交付
                }
                if (isUserCanOperateByRole("plan_admin")) {
                    showList.Can_Integration = true;//可集成
                    showList.CNIntegrate = true;//不可集成
                }
            }
        } else if ($scope.info.isAgent_Type == '5') {
            if ($scope.roleShow()) {
                if (isUserCanOperateByRole("plan_admin") || app.plan_StateShow || app.app_type == 'adempiere') {
                    showList.SwitchShow = true;
                }
            }

            if (typeof app.editionInfo != "undefined" && app.editionInfo != null && app.editionInfo != '' && app.editionInfo != undefined && app.editionInfo.editionNum != undefined) {
                if (isUserCanOperateByRole("plan_admin", "pm", "qa")) {
                    showList.Integrate = true;// 集成
                    showList.Cancel_Integrate = true;//取消集成
                    showList.Deliver = true;//交付
                    showList.Cancel_Deliver = true;//取消交付
                }
                if (isUserCanOperateByRole("plan_admin")) {
                    showList.Can_Integration = true;//可集成
                    showList.CNIntegrate = true;//不可集成
                }
            }
        } else if ($scope.info.isAgent_Type == '6') {
            if (isUserCanOperateByRole('admin')) {
                showList.SwitchShow = true;
            } else if ($scope.roleShow() && app.app_type == 'adempiere') {
                showList.SwitchShow = true;
            }
        }

        return showList
    };


    $scope.roleShow = function () {
        var isroleShow = false;
        if (isUserCanOperateByRole('ucloud_admin', 'plan_admin')) {
            isroleShow = true;
        } else {
            if (arrayContains($scope.info.userRole, $scope.info.vmInfo.type.toLowerCase())) {
                isroleShow = true
            } else if (arrayContains($scope.info.userRole, 'qa') && $scope.info.vmInfo.type.toLowerCase() == 'uat') {
                isroleShow = true
            } else if (arrayContains($scope.info.userRole, 'ops') && $scope.info.vmInfo.type.toLowerCase() == 'c') {
                isroleShow = true
            }
        }
        return isroleShow;
    };

    $scope.plan_show = function (app) {
        if (app.plan_StateShow == true && app.plan_project != undefined && app.editionInfo != undefined) {
            if (app.plan_project.hand_over_edition == app.editionInfo.editionNum) {
                return 'hand_over';//取消交付
            } else if (app.plan_project.integrationing_edition == app.editionInfo.editionNum) {
                return 'integrationing';//交付 取消集成
            } else if (app.plan_project.integration_edition == app.editionInfo.editionNum) {
                return 'integration';//集成
            } else if (app.plan_project.to_integration_edition == app.editionInfo.editionNum) {
                return 'to_integration_edition';//集成 取消转测
            } else if (app.plan_project.testing_edition == app.editionInfo.editionNum) {
                return 'testing';//转测 取消测试
            } else if (app.plan_project.to_test_edition == app.editionInfo.editionNum) {
                return 'to_test_edition';//测试 取消
            } else if ('default' == app.editionInfo.editionNum) {
                return '';
            } else {
                return true;
            }
        } else {
            return false;
        }
    };


    //数据库版本和工程版本图标显示
    $scope.showVersionIcon = function (app) {
        app.versionTip = '<div class="popover_div"><table class="table table-bordered popover_table">';

        var rtn = "";
        var desc = "";
        if (app.db_type == null
            || app.db_type == ''
            || app.db_name == null
            || app.db_name == '') {
            desc = "当前应用没有使用数据库.";
            rtn = "true";
        } else if (app.db_dump_create_date == null
            || app.db_dump_create_date == 'null'
            || app.app_package_create_date == null
            || app.app_package_create_date == 'null') {
            desc = "数据库导出时间或工程版本创建时间不存在";
            rtn = 'false';
        }
        if (rtn == "") {
            var date = (parse(app.db_dump_create_date).valueOf() - parse(app.app_package_create_date).valueOf()) / (1000 * 60 * 60 * 24);

            if (date < 0) {
                desc = "数据库版本比工程版本旧.若当前工程为要开发工程,请更新数据库.若当前工程为环境依赖工程,可忽略.";
                rtn = 'false';
            } else {
                desc = "数据库版本比工程版本新";
                rtn = 'true';
            }
        }
        if (desc != "") {
            if (rtn == 'false') {
                app.versionTip += '<tr><td class="popover_table_td yellow_color">DB/APP匹配：</td><td class="yellow_color">' + desc + '</td></tr>';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">DB/APP匹配：</td><td>' + desc + '</td></tr>';
            }
        }

        if (app.db_dump_create_date == null
            || app.db_dump_create_date == 'null') {
            app.versionTip += '<tr><td class="popover_table_td">数据版本时间戳:</td><td>无</td></tr>';
        } else {
            app.versionTip += '<tr><td class="popover_table_td">数据版本时间戳:</td><td>' + app.db_dump_create_date + '</td></tr>';
        }

        if (app.app_package_create_date == null
            || app.app_package_create_date == 'null') {
            app.versionTip += '<tr><td class="popover_table_td">应用版本时间戳:</td><td>无</td></tr>';
        } else {
            app.versionTip += '<tr><td class="popover_table_td">应用版本时间戳:</td><td>' + app.app_package_create_date + '</td></tr>';
        }

        if (app.version == '-1') {
            app.versionTip += '<tr><td class="popover_table_td red_color">部署分支:</td><td>未部署过分支</td></tr>';
        } else {
            if (app.version.indexOf("@") != -1) {
                if (app.plan_project != undefined && app.plan_project.project_name != null) {
                    if (app.version.split("@")[0] != app.plan_project.project_name
                        || (!$scope.info.isIntegrateIp && app.plan_project.to_test_edition != null && app.version.split("@")[1] != app.plan_project.to_test_edition)
                        || ($scope.info.isIntegrateIp && app.plan_project.integration_edition != null && app.version.split("@")[1] != app.plan_project.integration_edition)) {
                        app.versionTip += '<tr><td class="popover_table_td red_color">部署分支:</td><td class="red_color">' + app.version.replace('default', '临时版本') + '</td></tr>';
                        rtn = 'error';
                    } else {
                        app.versionTip += '<tr><td class="popover_table_td">部署分支:</td><td>' + app.version.replace('default', '临时版本') + '</td></tr>';
                    }
                } else {
                    app.versionTip += '<tr><td class="popover_table_td">部署分支:</td><td>' + app.version.replace('default', '临时版本') + '</td></tr>';
                }
            } else {
                app.versionTip += '<tr><td class="popover_table_td">部署分支:</td><td>' + app.version + '</td></tr>';
            }
        }
        if (app.onlineVersion != '') {
            app.versionTip += '<tr><td class="popover_table_td">线上分支:</td><td>' + app.onlineVersion + '</td></tr>';
        } else {
            app.versionTip += '<tr><td class="popover_table_td">线上分支:</td><td></td></tr>';
        }

        if (app.plan_project != undefined && app.plan_project.project_name != null) {
            if (app.version.indexOf("@") != -1 && app.version.split("@")[0] != app.plan_project.project_name) {
                app.versionTip += '<tr><td class="popover_table_td red_color">项目分支:</td><td class="red_color">' + app.plan_project.project_name + '</td></tr>';
                rtn = 'error';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">项目分支:</td><td>' + app.plan_project.project_name + '</td></tr>';
            }

        } else {
            app.versionTip += '<tr><td class="popover_table_td">项目分支:</td><td></td></tr>';
        }

        if (app.plan_StateShow) {
            if (app.plan_project.to_test_edition != null) {
                if (app.version.indexOf("@") != -1 && !$scope.info.isIntegrateIp && app.plan_project.to_test_edition != null && app.version.split("@")[1] != app.plan_project.to_test_edition) {
                    rtn = 'error';
                    app.versionTip += '<tr><td class="popover_table_td red_color">提测版本:</td><td class="red_color">' + app.plan_project.project_name + '@' + app.plan_project.to_test_edition + '</td></tr>';
                } else {
                    app.versionTip += '<tr><td class="popover_table_td">提测版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.to_test_edition + '</td></tr>';
                }
            } else {
                app.versionTip += '<tr><td class="popover_table_td">提测版本:</td><td></td></tr>';
            }
        }

        if (app.plan_StateShow) {
            if (app.plan_project.testing_edition != null) {
                app.versionTip += '<tr><td class="popover_table_td">测试中版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.testing_edition + '</td></tr>';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">测试中版本:</td><td></td></tr>';
            }
        }

        if (app.plan_StateShow) {
            if (app.plan_project.to_integration_edition != null) {
                app.versionTip += '<tr><td class="popover_table_td">申请转测版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.to_integration_edition + '</td></tr>';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">申请转测版本:</td><td></td></tr>';
            }
        }

        if (app.plan_StateShow) {
            if (app.plan_project.integration_edition != null) {
                if (app.version.indexOf("@") != -1 && $scope.info.isIntegrateIp && app.version.split("@")[1] != app.plan_project.integration_edition) {
                    app.versionTip += '<tr><td class="popover_table_td red_color">可以集成版本:</td><td class="red_color">' + app.plan_project.project_name + '@' + app.plan_project.integration_edition + '</td></tr>';
                    rtn = 'error';
                } else {
                    app.versionTip += '<tr><td class="popover_table_td">可以集成版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.integration_edition + '</td></tr>';
                }
            } else {
                app.versionTip += '<tr><td class="popover_table_td">可以集成版本:</td><td></td></tr>';
            }
        }
        if (app.plan_StateShow) {
            if (app.plan_project.integrationing_edition != null) {
                app.versionTip += '<tr><td class="popover_table_td">集测中版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.integrationing_edition + '</td></tr>';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">集测中版本:</td><td></td></tr>';
            }
        }
        if (app.plan_StateShow) {
            if (app.plan_project.hand_over_edition != null) {
                app.versionTip += '<tr><td class="popover_table_td">测试通过版本:</td><td>' + app.plan_project.project_name + '@' + app.plan_project.hand_over_edition + '</td></tr>';
            } else {
                app.versionTip += '<tr><td class="popover_table_td">测试通过版本:</td><td></td></tr>';
            }
        }

        if (app.plan_show_msg != null) {
            rtn = 'remind';
            app.versionTip += '<tr><td class="popover_table_td remind" >消息提醒:</td><td class="remind">' + app.plan_show_msg + '</td></tr>';
        }

        var msg = "";
        if (typeof app.last_msg != 'undefined' && app.last_msg != null && app.last_msg != '') {
            app.last_msg = app.last_msg.replace(new RegExp(/(\\n)/g), "<br>").replace(app.app_id + "_install", "安装" + app.app_name).replace(app.app_id + "_stop", "停止应用" + app.app_name).replace(app.app_id + "_restart", "重启应用" + app.app_name);
            if (app.last_msg.indexOf("[ERROR]") == 0) {
                msg = app.last_msg.substring(7, app.last_msg.length);
                rtn = 'error';
                app.versionTip += '<tr><td class="popover_table_td error" >错误信息:</td><td class="error">' + app.last_msg + '</td></tr>';
            }
        }

        if (app.delivery_Msg != null) {
            rtn = 'error';
            app.versionTip += '<tr><td class="popover_table_td error" >错误信息:</td><td class="error">' + app.delivery_Msg + '</td></tr>';
        }


        app.versionTip += '</table></div>';
        return rtn;
    };
    //log
    $scope.openShowLogModal = function (app) {

        var info = app;
        info.ip = $scope.ip;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'ucLogModal.html',
            controller: 'UCLogModalCtrl',
            // size: size,
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };

    //切换
    $scope.goSwitch = function (app) {
        var info = app;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'Switch.html',
            controller: 'SwitchCtrl',
            // size: size,
            resolve: {
                info: function () {
                    return app;
                }
            }
        });
    };

    $scope.link = function (projectName) {
        setStorage('project_go_back', '1');
        window.location.href = "#/menu/project/" + projectName;
    };

});


myApp.controller('UCLogModalCtrl', function ($scope, $uibModalInstance, $http, info, $interval, $sce) {

    $scope.tr = true;
    $scope.appLogs = "";
    $scope.pip_appLogs = "";
    $scope.pip_dbLogs = "";
    $scope.app = info;
    $scope.desc = '';

    $scope.appLog = function () {
        $.ajax({
            type: "put",
            url: getUCloudAddress($scope.app.ip) + '/apps/' + $scope.app.app_id + '/logs?log_type=app',
            dataType: "JSON",
            contentType: "application/json",
            async: false,
            success: function (data) {
                $scope.appLogs = "";
                $scope.appLogs = $sce.trustAsHtml(data);
            }
        });
    }

    $scope.pip_appLog = function () {
        $.ajax({
            type: "put",
            url: getUCloudAddress($scope.app.ip) + '/apps/' + $scope.app.app_id + '/logs?log_type=pip-app',
            dataType: "JSON",
            contentType: "application/json",
            async: false,
            success: function (data) {
                $scope.pip_appLogs = "";
                $scope.pip_appLogs = $sce.trustAsHtml(data);
            }
        });

    }

    $scope.pip_dbLog = function () {
        $.ajax({
            type: "put",
            url: getUCloudAddress($scope.app.ip) + '/apps/' + $scope.app.app_id + '/logs?log_type=pip-db',
            dataType: "JSON",
            contentType: "application/json",
            async: false,
            success: function (data) {
                $scope.pip_dbLogs = "";
                $scope.pip_dbLogs = $sce.trustAsHtml(data);
            }
        });
    }

    $scope.Refresh = function () {
        $scope.appLog();
        $scope.pip_appLog();
        $scope.pip_dbLog();
        return false;
    }

    $scope.Refresh();
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});


//切换
myApp.controller('SwitchCtrl', function ($scope, $uibModalInstance, $http, info, $interval, $sce) {
    $scope.app = info;
    // project变动
    $scope.projectChange = function (app) {
        if (app.app_type == 'adempiere') {
            $http.post(java_url + '/beetle/uCloud/adEditionList', {
                projectName: app.projectInfo.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                }
                ;
                app.editionList = data.data.list;
                if (app.editionNum == '') {
                    app.editionInfo = data.data.list[0];
                    app.editionNum = app.editionInfo.editionNum;
                } else {
                    var count = 0;
                    angular.forEach(data.data.list, function (edi) {
                        if (edi.editionNum == app.editionNum) {
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if (count == 0) {
                        app.editionInfo = data.data.list[0];
                    }
                }
                ;
            });
        } else {
            $http.post(java_url + '/beetle/project/editionInfoList', {
                projectName: app.projectInfo.projectName,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                }
                ;
                app.editionList = data.data.list;
                if (app.editionNum == '') {
                    if (data.data.list.length > 1) {
                        app.editionInfo = data.data.list[1];
                    } else {
                        app.editionInfo = data.data.list[0];
                    }
                    app.editionNum = app.editionInfo.editionNum;
                } else {
                    var count = 0;
                    angular.forEach(data.data.list, function (edi) {
                        if (edi.editionNum == app.editionNum) {
                            count = 1;
                            app.editionInfo = edi;
                        }
                    });
                    if (count == 0) {
                        if (data.data.list.length > 1) {
                            app.editionInfo = data.data.list[1];
                        } else {
                            app.editionInfo = data.data.list[0];
                        }
                    }
                }
                ;
            });
        }
    };

    $scope.editionChange = function (app) {
        app.editionNum = app.editionInfo.editionNum;
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});